package demo1;

import java.util.Arrays;

public class MyArrayList {
    private int[] elem;//用来存放数据元素
    private int usedSize;//代表当前顺序表中有效个数//引用类型不初始化默认为0

    private static final int DEFAULT_SIZE = 2;

    /**
     * 默认容量的构造方法
     */
    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    /**
     * 指定容量的构造方法
     * @param initCapacity
     */
    public MyArrayList(int initCapacity) {
        this.elem = new int[initCapacity];
    }
    //打印顺序表中所有的数据
    public void display(){
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
    }
    //新增元素，默认在数组最后新增
    public void add(int data) {
        if(isFull()){
            //扩容
            this.elem = Arrays.copyOf(this.elem , 2*this.elem.length);

        }
        this.elem[this.usedSize] = data;
        this.usedSize++;
    }

    public boolean isFull(){
        if(this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }
    //在pos位置新增元素
    public void add(int pos , int data){
        if(pos < 0 || pos > this.usedSize){
            throw new PosOutfBoundsException("位置不合法");
            //System.out.println("位置不合法");
            //return;
        }
        if(isFull()){
            //扩容
            this.elem = Arrays.copyOf(this.elem , 2*this.elem.length);
        }

        for (int i = this.usedSize; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }

        this.elem[pos] = data;
        this.usedSize++;//因为元素只能一个一个插入，所以usedSize从0开始加
    }
    public boolean contains(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    //查询是否有toFind
    public int indexOf(int toFind){
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    //获取pos下标的数
    public int get(int pos){
        if(pos < 0 || pos >= this.usedSize){
            throw new PosOutfBoundsException("位置不合法");
        }
        return this.elem[pos];
    }
    //给pos位置的值设置为value
    public void set(int pos , int value){
        if(pos < 0 || pos >= this.usedSize){
            throw new PosOutfBoundsException("位置不合法");
        }

    }

}

